import React, { Component } from 'react'
import { View,Image, Text ,TouchableOpacity, TouchableOpacityBase} from 'react-native'
import { Input,Icon } from 'react-native-elements';
import {pxToDp,screenWidth} from '../../../utils/stylesKits'
import SvgUri from 'react-native-svg-uri'
import {male,female} from '../../../soures/fonts/iconSvg'
import DatePicker from 'react-native-datepicker';
import Geo from '../../../utils/Geo'
import Picker from 'react-native-picker';
import CityJson from '../../../utils/citys.json'
import THButton from '../../../components/THButton'
import Toast from '../../../utils/Toast'
import ImagePicker from 'react-native-image-crop-picker';
import {Overlay} from 'teaset'
import {inject,observer} from 'mobx-react'
import { ACCOUNT_CHECKHEADIMAGE ,ACCOUNT_REGINFO} from '../../../utils/pathMap';
import request from '../../../utils/request';
@inject('rootStore')
@observer
class UserInfo extends Component {
    state={
        //昵称
        nickname: "",
        //性别
        gender: "男",
        //生日
        birthday: "",
        //城市
        city: "",
        //头像
        header: "",
        //经度
        lng: "",
        //纬度
        lat: "",
        //详细地址
        address: ""
    }

    //选择性别
    changeGender = (gender)=>{
        return ()=>{
            this.setState({ gender });
        }
    }
    //选择城市
    choiceCity=()=>{
        Picker.init({
            pickerData: CityJson,
            selectedValue: ["北京", "北京"],
            wheelFlex: [1, 1, 0], // 显示省和市
            pickerConfirmBtnText: "确定",
            pickerCancelBtnText: "取消",
            pickerTitleText: "选择城市",
            onPickerConfirm: data => {
                // data =  [广东，广州，天河]
                this.setState(
                {
                    city: data[1]
                }
                );
            }
        });
        Picker.show();
    }
    
    //点击设置头像
    chooseHeadImg= async ()=>{
        /**
         * 1 校验用户昵称 生日 当前地址 city
         * 2 使用图片剪裁插件
         * 3 将选择好的图片上传到后台
         * 4 提交参数到后台 -> 完成 信息填写
         * 5 成功 
         *      1 极光的注册 极光的登录
         *      2 跳转到交友 - 首页
         */
        const {nickname,birthday,city} = this.state
        if(!nickname || !birthday || !city){
            Toast.sad('用户昵称或者生日或者地址不合法',2000,'center')
            return
    }

    //获取选中后的图片
    const image= await ImagePicker.openPicker({
        width: 300,
        height: 400,
        cropping: true
        })
        console.log("image=",image)
        let overlayView = (
            <Overlay.View
                style={{flex:1,
                    backgroundColor:'#000',
                    width:'100%',
                    alignItems: 'center', 
                    justifyContent: 'center'}}
                modal={true}
                overlayOpacity={0}
                ref={v => this.overlayView = v}
            >
                <View
                    style={{
                        marginTop:pxToDp(30),
                        alignSelf:"center",
                        alignItems:'center', 
                        justifyContent: 'center',
                        width:pxToDp(334),
                        height:pxToDp(334),
                        position:"relative"
                    }}
                >
                    <Image 
                        style={{width:'100%',
                            height:"100%",
                            position:'absolute',
                            left:0,top:0,zIndex:100
                        }} 
                        source={require("../../../soures/scan.gif")}
                    />
                    <Image
                        style={{
                            width:'60%',
                            height:'60%'
                        }}
                        source={{uri:image.path}}
                    />
                </View>
            </Overlay.View>
        );
        Overlay.show(overlayView);

        const res0 = await this.sendHeadImg(image)
        if(res0!=='10000'){
            this.setState({header:'/upload/13828459787.jpg'})
        }

        this.loginReginfo()
    }

    //填写资料
    loginReginfo= async ()=>{
        let params = this.state
        console.log('params=',params)
       const res = request.privatePost(ACCOUNT_REGINFO,params,{
           headers:{
                "Content-Type": "application/json"
           }
       }) 
       console.log('loginReginfo=',res)
       if(res.code==='10000'){

       }else{
            //关闭扫描遮罩
            this.overlayView.close()
            //给出用户提示
            Toast.smile('恭喜操作成功',2000,'center')
            //跳转到交友页面
            
       }
       
    }

    //发送头像到后台
    sendHeadImg = (image)=>{
        //构造参数发送到后台
        let formData = new FormData()
        formData.append('headPhone',{
            uri:image.path,
            type:image.mime,
            name:image.path.split('/').pop()
        })
        //执行头像上传
        return request.privatePost(ACCOUNT_CHECKHEADIMAGE,formData,{
            headers:{
                "Content-Type": "multipart/form-data"
            }
        })
    }


    async componentDidMount(){
        const res = await Geo.getCityByLocation()
        const {formatted_address} = res.regeocode
        const {city} = res.regeocode.addressComponent
        const lng = res.regeocode.addressComponent.streetNumber.location.split(',')[0]
        const lat = res.regeocode.addressComponent.streetNumber.location.split(',')[1]
        this.setState({
            address:formatted_address,
            city,
            lng,
            lat
        })
        console.log(res)
    }
    render() {
        const {nickname,gender,birthday,city} = this.state
        return (
            <View style={{flex:1,backgroundColor:'#fff',padding:pxToDp(20)}}>
                <View>
                    <Text style={{fontSize:pxToDp(20),color:'#666',fontWeight:'600'}}> 填写资料 </Text>
                    <Text style={{fontSize:pxToDp(20),color:'#666',fontWeight:'600'}}> 提升我的魅力 </Text>
                </View>

                {/* 性别 */}
                <View style={{marginTop:pxToDp(20)}}>
                    <View style={{width:"60%",flexDirection:'row',alignSelf:'center',justifyContent:"space-around"}}>
                        <TouchableOpacity 
                            disabled={gender==='男'}
                            style={{width:pxToDp(60),
                            height:pxToDp(60),
                            borderRadius:pxToDp(30),
                            backgroundColor:gender==='男'?"red":"#eee",
                            justifyContent:"center",
                            alignItems:'center'}}
                            onPress={this.changeGender('男')}
                        >
                            <SvgUri svgXmlData={male} width={pxToDp(40)} height={pxToDp(40)}/>  
                        </TouchableOpacity>
                        <TouchableOpacity 
                            disabled={gender==='女'}
                            style={{width:pxToDp(60),
                            height:pxToDp(60),
                            borderRadius:pxToDp(30),
                            backgroundColor:gender==='女'?"red":"#eee",
                            justifyContent:"center",
                            alignItems:'center'}}
                            onPress={this.changeGender('女')}    
                        >
                            <SvgUri svgXmlData={female} width={pxToDp(40)} height={pxToDp(40)}/>  
                        </TouchableOpacity>
                    </View>
                </View>
                {/* 性别 结束 */}

                {/* 昵称 开始 */}
                    <View>
                        <Input
                            value={nickname}
                            placeholder='设置昵称'
                            onChangeText={(nickname)=>this.setState({nickname})}
                        />
                    </View>
                {/* 昵称 结束 */}

                {/* 日期 开始 */}
                <DatePicker
                    androidMode="spinner"
                    style={{ width: "100%" }}
                    date={birthday}
                    mode="date"
                    placeholder="设置生日"
                    format="YYYY-MM-DD"
                    confirmBtnText="确定"
                    cancelBtnText="取消"
                    customStyles={{
                        dateIcon: {
                            display: "none"
                        },
                        dateInput: {
                            marginLeft: pxToDp(10),
                            borderWidth: 0,
                            borderBottomWidth: pxToDp(1.1),
                            alignItems: "flex-start",
                            paddingLeft: pxToDp(4)
                        },
                        placeholderText: {
                            fontSize: pxToDp(16),
                            color: "#afafaf"
                        }
                    }}
                    onDateChange={(birthday) => { this.setState({ birthday }) }}
                />
                {/* 日期 结束 */}

                {/* 地址 开始 */}
                    <View style={{marginTop:pxToDp(20)}}>
                        <TouchableOpacity onPress={this.choiceCity} activeOpacity={1}>
                            <Input
                                value={'当前定位:'+city}
                                style={{
                                    fontSize: pxToDp(16),
                                }}
                                disabled={true}
                            >
                            </Input>
                        </TouchableOpacity>
                    </View>
                {/* 地址 结束 */}

                {/* 选择头像 开始 */}
                     <View>
                        <THButton
                            style={{
                                height:pxToDp(40),
                                borderRadius:pxToDp(20),
                                alignSelf:'center'
                            }}
                            onPress={this.chooseHeadImg}
                        >设置头像</THButton>   
                    </View>           
                {/* 选择头像 结束 */}
            </View>
        )
    }
}

export default UserInfo